﻿<%@ Page Title="Grocery" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"  CodeFile="Grocery.aspx.cs" Inherits="Grocery" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    
   <%-- <link href="css/popup.css" rel="stylesheet" type="text/css" media="all" />--%>
<script type="text/javascript" src="js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="js/share.js"></script>
<script type="text/javascript" src="js/popup.js"></script>
<script src="js/fraction-0.2.js" type="text/javascript"></script>
<script src="js/Ratio-0.4.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var GlobalReiceID = '';
    var IngreDientEmail = '';
    var DepartEmail = '';
    var htmlDepartment = '';
    var cbDepartID = 0;
    var cbRecipeID = 0;
    var titleEmail = '';
    $(document).ready(function () {
        
        GlobalReiceID = '<%=Session["RecipeId"]%>';
        document.getElementById('<%=SendDepart.ClientID%>').value = '';
        GetRecipeIngredientUser();
        GetRecipeIngredientUserByDeptView();
        ShowRecipeIngredientUserRecipeView();

        $("#dialogEmail").dialog({
            resizable: false,
            width: 270,
            modal: true,
            autoOpen: false,
            buttons: {
                "Yes": function () {
                    $(this).dialog("close");
                    //window.location = "Logout.aspx";
                }
            }
        });
        
    });

    function isInteger(n) {
        return !isNaN(n);
    }

    function ShowRecipeIngredientUserRecipeView() {
        var linkDepart = "images/radio_check.jpg";
        var linkRecipe = "images/radio_uncheck.jpg";
        document.getElementById('<%=Check.ClientID%>').value = 'true';
        $('#liRecipe').ready(function () {
            $('#liRecipe').css('background-image', 'url(' + linkRecipe + ')');
            $('#liDepart').css('background-image', 'url(' + linkDepart + ')');

            $('#divGroceryDepart').css('display', 'inherit');
            $('#divGroceryRecipe').css('display', 'none');

        });

        $('#liRecipe').click(function () {
            document.getElementById('<%=Check.ClientID%>').value = 'false';
            linkDepart = "images/radio_uncheck.jpg";
            linkRecipe = "images/radio_check.jpg";

            $('#liRecipe').css('background-image', 'url(' + linkRecipe + ')');
            $('#liDepart').css('background-image', 'url(' + linkDepart + ')');

            $('#divGroceryDepart').css('display', 'none');
            $('#divGroceryRecipe').css('display', 'inherit');
        });

        $('#liDepart').click(function () {
            document.getElementById('<%=Check.ClientID%>').value = 'true';
            linkDepart = "images/radio_check.jpg";
            linkRecipe = "images/radio_uncheck.jpg";
            $('#liRecipe').css('background-image', 'url(' + linkRecipe + ')');
            $('#liDepart').css('background-image', 'url(' + linkDepart + ')');

            $('#divGroceryDepart').css('display', 'inherit');
            $('#divGroceryRecipe').css('display', 'none');
        });
    }

    function GetRecipeIngredientUserByDeptView() {
        $('#divGroceryDepart').html('');
        //alert(GlobalReiceID);
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/getIngredientUserByListRecipeID",
            data: "{'RecipeID':'" + GlobalReiceID + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                getDepart(response.d);
            },
            error: function (response) {
            }
        });
    }

    function getIngredientByServing() {
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/getRecipeIngredientUserByListRecipeID",
            data: "{'RecipeID':'" + GlobalReiceID + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                getDepart(getIngredientName(response));
            },
            error: function (response) {
            }
        });
    }

    function getIngredientName(response) {
        var listIngredient = response.d;
        var object = '';
        for (var i = 0; i < listIngredient.length; i++) {
            var obj = listIngredient[i].IngredientName;
            if ($('#txtServing').val() != '') {
                obj = ChangeServingSize(obj, listIngredient[i].Serving, $('#txtServing').val());
            }
            object += obj + '+';
        }
        return object;
    
    }


    function getDepart(IngredientName) {
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/getIngredientDeptDetail_1",
            data: "{'ingredientName':'" + IngredientName + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $('#divGroceryDepart').html('');
                BindDeparts(response);
            },
            error: function (response) {
            }
        });


    }

    function BindDepart(response) {
        //alert(response.d);

        var depart = response.d;
        htmlDepartment = '';
        titleEmail += ')</strong><br/><hr></hr>';
        DepartEmail = titleEmail;
        for (var j = 0; j < depart.length; j++) {
            var IngredientDeptDetail = depart[j].ingreDeptDetails;
            var grodpt = IngredientDeptDetail[0].GroDept;
            htmlDepartment = '<div>';
            htmlDepartment += '<div class="depart-head-row">';
            htmlDepartment += '&nbsp;&nbsp;<b>' + grodpt + '</b>&nbsp;&nbsp;';
            htmlDepartment += '</div>';
            DepartEmail += '<strong>' + grodpt + '</strong>+';
            for (var i = 0; i < IngredientDeptDetail.length; i++) {
                htmlDepartment += '<div class="depart-row">';
                var ingre = IngredientDeptDetail[i].ingre;
                htmlDepartment += '<span ><input type="checkbox" checked="true" class="" /> </span>';
                htmlDepartment += '<a class="css-label1">' + ingre + '</a>';
                htmlDepartment += '</div>';
                DepartEmail += ingre + '+';
            }
            htmlDepartment += '<hr></hr>';
            htmlDepartment += '</div>';
            DepartEmail += '<hr></hr>';
            $('#divGroceryDepart').append(htmlDepartment);
            document.getElementById('<%=SendDepart.ClientID%>').value = DepartEmail;
        }
    }

    function BindDeparts(response) {
        //alert(response.d);

        var depart = response.d;
        htmlDepartment = '';
        titleEmail += ')</strong><br/><hr></hr>';
        DepartEmail = titleEmail;
        for (var j = 0; j < depart.length; j++) {
            var IngredientDeptDetail = depart[j].ingreDeptDetails;
            var grodpt = IngredientDeptDetail[0].GroDept;
            htmlDepartment = '<div>';
            htmlDepartment += '<table><tbody>';
            htmlDepartment += '<tr class="depart-head-row"><td class="td-image""></td><td><p>' + grodpt + '</p></td></tr>';
            DepartEmail += '<strong>' + grodpt + '</strong>+';
            for (var i = 0; i < IngredientDeptDetail.length; i++) {
                var ingre = IngredientDeptDetail[i].ingre;
                htmlDepartment += '<tr class="depart-row">';
                htmlDepartment += '<td><input type ="checkbox" checked="true" id="cbDepart' + cbDepartID + '" onclick="javascript:check(this.id,false)"  value="' + ingre + '"></td>'
                htmlDepartment += '<td><p class="css-label1">' + ingre + '</p></td></tr>';
                DepartEmail += ingre + '+';
                cbDepartID++;
            }
            htmlDepartment += '</tbody></table>';
            htmlDepartment += '</div>';
            DepartEmail += '<hr></hr>';
            $('#divGroceryDepart').append(htmlDepartment);
            document.getElementById('<%=SendDepart.ClientID%>').value = DepartEmail;
        }

    }

    function getIngredientNameUserByRecipeID(recipeID) {
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/getIngredientNameUserByRecipeID",
            data: "{'RecipeID':'" + recipeID + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
            },
            error: function (response) {
            }
        });
    }


    function GetRecipeIngredientUser() {
        var ReiceIdSession = '<%=Session["RecipeId"]%>';
        var RecipeIDList = ReiceIdSession.split(',');
        var html = '';
        $('#divGroceryRecipe').html(html);
        document.getElementById('takeIngredient').value = '';
        document.getElementById('<%=SendIngredient.ClientID%>').value = '';
        document.getElementById('<%=SendDepart.ClientID%>').value = '';
        titleEmail = '<strong>INGREDIENT LIST OF(';
        DepartEmail = '';
        $.each(RecipeIDList, function (key, RecipeIDList) {
            var Recipe = RecipeIDList.split(' ');
            var serving = $('#txtServing').val();
            var data = "";
            var url = "";
            if (serving != "") {
            }
            url = "PIMService.asmx/getRecipeIngredientUserByRecipeID";
            data = "{'RecipeID':'" + Recipe + "'}";
            if (Recipe != "") {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        BindRecipeIngredientUser(response, html);
                    },
                    error: function (response) {
                    }
                });
            }
        });
    }

    function RemoveRecipe(recipeId) {
        
        $("#" + recipeId).remove();
        GlobalReiceID = GlobalReiceID.replace(recipeId, '');
        getIngredientNameUserByRecipeID(GlobalReiceID);
    }

    function BindRecipeIngredientUser(response, html) {
        var RecipeIngredient = response.d;
        var RecipeName = RecipeIngredient[0].RecipeName;
        var RecipeId = RecipeIngredient[0].RecipeID;
        var Serving = RecipeIngredient[0].Serving;
        titleEmail += RecipeName + ','
        html += '<section id="' + RecipeId + '">';
        html += '<table class="table-grocery"><tbody><tr class="tr-image">';
        html += '<td class="td-image"><img class="image-grocery" src="../' + RecipeIngredient[0].RecipeImage + '" /></td>';
        html += '<td><p>' + RecipeName + '&nbsp;&nbsp;Serving: ' + Serving + '</p></td>';
        html += '<td style="width:30px;" onclick="javascript:RemoveRecipe(' + RecipeId + ')" ><img src="images/img02.jpg" style="width:20px;height:5px;" /></td></tr>';
        document.getElementById('<%=shareIngredient.ClientID%>').value += RecipeName + " \n";
        IngreDientEmail = '<strong>' + RecipeName + "\t Serving:" + Serving + "</strong>+";
        for (var i = 0; i < RecipeIngredient.length; i++) {
            var RecipeIngerdientId = RecipeIngredient[i].RecipeIngredientUserID;
            var RecipeIngredientUserName = RecipeIngredient[i].IngredientName;
            if ($('#txtServing').val() != '') {
                RecipeIngredientUserName = ChangeServingSize(RecipeIngredientUserName, Serving , $('#txtServing').val());
            }
            var RecipeImage = RecipeIngredient[i].RecipeImage;
            html += '<tr class="tr-row"><td ><input type="checkbox" checked="true" id="cbRecipe' + cbRecipeID + '" onclick="javascript:check(this.id,true)" value="' + RecipeIngredientUserName + '"/></td>';
            html += '<td ><p class="css-label1">' + RecipeIngredientUserName + '</p></td>';
            document.getElementById('takeIngredient').value += RecipeIngredientUserName + '+';
            document.getElementById('<%=shareIngredient.ClientID%>').value += "\t -" + RecipeIngredientUserName + " \n";

            IngreDientEmail += RecipeIngredientUserName + '+';
            cbRecipeID++;
        }
        html += '</tbody></table>';
//        html += '<hr></hr>';
        html += '</section>';
        document.getElementById('<%=SendIngredient.ClientID%>').value += IngreDientEmail + '<hr></hr>';
        //alert(IngreDientEmail);
        $('#divGroceryRecipe').append(html);
    }

    function check(id, isRecipe) {
        var checked = $('#' + id).is(":checked");
        var value = $('#' + id).val();
        if (checked) {
            $('#' + id).parent().parent().removeClass('remove');
            $('#' + id).attr('checked', 'checked')

        } else {
            $('#' + id).parent().parent().addClass('remove');
            $('#' + id).removeAttr('checked');
        }
        //alert($('#' + id).val());
        if (isRecipe) {
            //alert('recipe');
            var $control = $('#divGroceryDepart input:checkbox[value="' + value + '"]');
            if ($control.is("::checked"))
                $control.removeAttr('checked');
            else
                $control.attr('checked', 'checked')
        } else {
            var $control = $('#divGroceryRecipe input:checkbox[value="' + value + '"]');
            if ($control.is("::checked"))
                $control.removeAttr('checked');
            else
                $control.attr('checked', 'checked')

        }
        
        //alert(checked);
        //$('#' + id).parent().addClass('remove');
        
    }

    function clearGrocery() {
        $('#divGroceryRecipe').html('');
        $('#divGroceryDepart').html('');
        return true;
    }

    function getBodyEmail(id) {
       // var $newHTML = $('#' + id).clone().find(".remove").remove().end();
        //$newHTML = $newHTML.clone().find("img").remove().end();
        var html = $('#' + id).html();
        var $data = $(html);
        var textbody = $data.find("img").remove().end().html();
        return textbody;
    }

    function SendEmail() {
        if (document.getElementById('<%=txtEmail.ClientID%>').value == '') {
            alert('Please input email address.');
            return false;
        }
        var username = '<%=Session["UserName"]%>';
        var body = '';
        if (document.getElementById('<%=Check.ClientID%>').value == 'true') {
            body = titleEmail + getBodyEmail('divGroceryDepart');
            body = body.replace('class="depart-head-row"', 'style="font-weight:bold;"');
        } else {
            body = titleEmail + getBodyEmail('divGroceryRecipe');
            body = body.replace('class="depart-head-row"', 'style="font-weight:bold;"');
        }
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/SendEmail",
            data: "{'username':'" + username + "','email':'" + document.getElementById('<%=txtEmail.ClientID%>').value + "','body':'" + body + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                //alert(response.d);
                if (response.d)
                    $('#dialogEmail').dialog('open');
                else
                    alert('Email is not sent.');
                $("#<%=txtEmail.ClientID%>").val('');
                $("div.close").click();
            },
            error: function (response) {
            }
        });
        return false;

    }

    function getTextCheckBox() {

        alert($(':checkbox[name=Ingredient]').next('p').text());
        return false;
    }

    function ChangeServingSize(IngrediengName, Serving, ServingSize) {
        var pattern = /^\S+/;
        var pattern1 = /[^a-z]+/gi;
        var osv = IngrediengName.match(pattern);
        if (osv == null) osv = 1;
        var regixchar = osv.toString().match(pattern1);
        if (regixchar == null) {
            //alert(regixchar);
            return IngrediengName;
        }
        osv = regixchar;
        var newosv;
        if (osv.toString().indexOf('-') > -1) {
            //alert('1');
            var arr = osv.toString().split('-');
            if (!arr[0].trim())
                return IngrediengName;
            var newsering1 = arr[0] * ServingSize / Serving;
            var newserving2 = arr[1] * ServingSize / Serving;
            var newserving = Ratio.parse(newsering1).simplify().toLocaleString() + '-' + Ratio.parse(newserving2).simplify().toLocaleString();
            return IngrediengName.replace(osv, newserving);
        }
        {
            var newosv = convertfraction(osv);
            var newserving = newosv * ServingSize / Serving;
            var nsv = Ratio.parse(newserving).simplify().toLocaleString();
            return IngrediengName.replace(osv, nsv)
        }
    } 


//    function ChangeServingSize(IngrediengName, Serving, ServingSize) {
//        var pattern = /^\S+/;
//        var osv = IngrediengName.match(pattern);
//        var regixchar = osv.toString().match(/[^a-z]+/gi);
//        //alert(regixchar);
//        if (osv == null) osv = 1;
//        if (regixchar != null) {
//            return IngrediengName;
//        }
//        osv = regixchar;
//        var newosv;
//        if (osv.toString().indexOf('-') > -1) {
//            var arr = osv.toString().split('-');
//            if (!arr[0].trim())
//                return IngrediengName;
//            var newsering1 = arr[0] * ServingSize / Serving;
//            var newserving2 = arr[1] * ServingSize / Serving;
//            var newserving = Ratio.parse(newsering1).simplify().toLocaleString() + '-' + Ratio.parse(newserving2).simplify().toLocaleString();
//            return IngrediengName.replace(osv, newserving);
//        } 
//        {
//            var newosv = convertfraction(osv);

//            var newserving = newosv * ServingSize / Serving;
//            var nsv = Ratio.parse(newserving).simplify().toLocaleString();
//            return IngrediengName.replace(osv, nsv)
//        }

//    }
    function convertfraction(x) {
            var y = x.toString().split(' ');
            if (y.length > 1) {
                var z = y[1].split('/');
                return +y[0] + (z[0] / z[1]);
            }
            else {
                var z = y[0].split('/');
                if (z.length > 1) {
                    return z[0] / z[1];
                }
                else {
                    return z[0];
                }
            }
        
    }

    function AddAdditional() {
        if ($("#txtAdditional").val() == '') {
            alert('Please input additional.');
            return false;
        }

        var addInfre = '';
        DepartEmail = '';
        var divAdditionalIngre = $('#AdditionalIngre');
        if (divAdditionalIngre.length > 0) {
            DepartEmail += $("#txtAdditional").val() + '+<hr></hr>';
            addInfre += '<tr><td><input type="checkbox" id="cbRecipe' + cbRecipeID + '" onclick="javascript:check(this.id)" checked="true"  value="' + $("#txtAdditional").val() + '" name="Ingredient" /></td>'
            addInfre += '<td ><p class="css-label1">' + $("#txtAdditional").val() + '</p></td></tr>';
            $('#trAdd').after(addInfre);
            cbRecipeID++;
        } else {
            DepartEmail = '<strong>Additional</strong>+';
            DepartEmail += $("#txtAdditional").val() + '+<hr></hr>';
            addInfre = '<section id="0"><table id="AdditionalIngre" class="table-grocery"><tbody>';
            addInfre += '<tr id="trAdd" class="tr-image" style="height:40px"><td class="td-image""></td><td><p>Additional<p></td>';
            addInfre += '<td style="width:30px;" onclick="javascript:RemoveRecipe(0)" ><img src="images/img02.jpg" style="width:20px;height:5px;" /></td></tr>';
            addInfre += '<tr class="tr-row" ><td><input type="checkbox" id="cbRecipe' + cbRecipeID + '" onclick="javascript:check(this.id)" checked="true" value="' + $("#txtAdditional").val() + '" name="Ingredient" /></td>'
            addInfre += '<td ><p class="css-label1">' + $("#txtAdditional").val() + '</p></td></tr></tbody></table></section>';
            $('#divGroceryRecipe').prepend(addInfre);
            cbRecipeID++;
        }
        var addDepart = '';
        var divAddDepart = $('#AdditionalDepart');
        if (divAddDepart.length > 0) {
            addDepart = '<tr class="depart-row"><td><input type="checkbox" id="cbDepart' + cbDepartID + '" onclick="javascript:check(this.id)" checked="true" value="' + $("#txtAdditional").val() + '" name="Ingredient" />';
            addDepart += '<td><p class="css-label1">' + $("#txtAdditional").val() + '</p><td></tr></tbody></table>';
            divAddDepart.after(addDepart);
        }
        else {
            addDepart = '<table ><tbody><tr class="depart-head-row"><td class="td-image"></td><td><p>Additional</p></td></tr>';
            addDepart += '<tr id="AdditionalDepart" class="depart-row" ><td><input type="checkbox" id="cbDepart' + cbDepartID + '" onclick="javascript:check(this.id)" checked="true" value="' + $("#txtAdditional").val() + '" name="Ingredient" /></td>';
            addDepart += '<td><p class="css-label1">' + $("#txtAdditional").val() + '</p><td></tr></tbody></table>';
            $('#divGroceryDepart').prepend(addDepart);
        }

        document.getElementById('<%=SendDepart.ClientID%>').value += DepartEmail;
        document.getElementById('<%=SendIngredient.ClientID%>').value += DepartEmail;
        $("#txtAdditional").val('');
        return false;
    }

    function changeServing() {
        GetRecipeIngredientUser();
        getIngredientByServing();
    }

</script>

<section id="bg_content01">
	<h2>
        <img src="images/title01.jpg"  alt="Grocery List" style="float:left; margin-right:20px;" width="96" height="25">
        <div class="left01 shareButton">
            <a href="#" class="topopup">
                <img src="images/mail.png" class="imgIcon2"  />
            </a>
        </div>
    </h2>

    <div class="clearfix clear mar_b10">
        <div class="clearfix">
            <div >
                <select id="txtServing" onchange="changeServing();" style="padding:8px; width:260px">
                  <option value="">Serving size</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                  <option value="17">17</option>
                  <option value="18">18</option>
                  <option value="19">19</option>
                  <option value="20">20</option>
                </select>
            </div>
        </div>
        <div class="clearfix" style="margin-top:10px;">
            <div class="">
                <input name="additional" type="text" placeholder="Additional"  class="input1" style="width:240px"  id="txtAdditional" />
                <button onclick="return AddAdditional();" class="button-form" >Add</button>
            </div>
        </div>
    </div>
    <div class="clearfix clear mar_b10">
        
        <div class="right01">
            <label id="liRecipe" for="radio1" class="css-label">
                Recipe view</label>
            <label id="liDepart" for="radio1" class="css-label">
                Department view</label>
        </div>
        <div style="float:right">
            <asp:Button ID="btnClear" runat="server"  CssClass="clear-btn" Text="Clear all" OnClientClick="return clearGrocery();"  OnClick="btnClear_Click"/>
        </div>
        </div>
        <div id="divGroceryRecipe" style="display:none"></div>
        <div id="divGroceryDepart" style="display:inherit"></div>
        <div style="clear: both"></div>
       
        <div id="toPopup">

        <div class="close"></div>
       	<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
		<div id="popup_content"> <!--your content start-->
            <p class="text-field">
            Email:
            </p>
            <p class="ip-text">
            <asp:TextBox ID="txtEmail" CssClass="input-trpr" runat="server"></asp:TextBox>
            </p>
            <%--<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator7" ControlToValidate="txtEmail"  ErrorMessage="*" ></asp:RequiredFieldValidator>--%>
            <%--<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator4" ControlToValidate="txtEmail"  ErrorMessage="*" />--%>
                    <asp:RegularExpressionValidator   
                        ID="RegularExpressionValidator1"  
                        runat="server"   
                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"  
                        ControlToValidate="txtEmail"  
                        ErrorMessage="Please input invalid email address." 
                         CssClass="errormsg" 
                        >  
                    </asp:RegularExpressionValidator>
        </div> <!--your content end-->
        <div style="text-align:center; margin-bottom:10px;">
            <asp:Button ID="btnSend" runat="server" OnClientClick="return SendEmail();" class="button-form" Text="Send" OnClick="btnSendEmail_Click"/>
        </div>
        </div>

     <input id="takeIngredient" type="hidden" />
     <input id="shareIngredient" runat="server" type="hidden" />
     <asp:HiddenField id="SendIngredient" runat="server" />
      <asp:HiddenField id="SendDepart" runat="server" />
      <asp:HiddenField id="Check" runat="server" />
      <div id="dialogEmail" class="message-diaglog">
                  <p>Email is sent, please check your email to view detail.</p>
                </div>
</section>
</asp:Content>

